import ScrollBarLayout from '@/components/ScrollBarLayout';
import Cls from 'classnames';
import { useEffect, useMemo, useState } from 'react';
import pageStyles from '@/common/pageLayout.less';
import { DescriptionsType } from '@/components/DescriptionsType';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { getCompanyID, getKeyRouter, getPosIDs, getTenantID, getUserDepID, getUserID } from '@/utils';
import { getUpdateConfig } from '../mconfig/UpdateConfig';
import { connect, history } from 'umi';
import { Col, Form, Row, Spin, Tabs, Space, Button, message, Modal } from 'antd';
import React from 'react';
import { ILoadMapTypeAll } from '@/common';
import { WorkflowChedkRecord, WorkflowNoDefaultTable, WorkflowSwitchModal } from '@/components/WorkflowCommonCopy';
import { orderType as LYOrderType, LYflowBusinessType, requestController as LYrequestController } from '../common/FormatUse';
import { orderType as TKOrderType, requestController as TKrequestController } from '../common/FormatReturn';
import '../common/style.less';
import { AcquisitionManageContext, IAcquisitionActionEnum, useAcquisitionManageReducer } from '../mconfig';
import { OpenAssetModal } from '../mconfig/OpenAssetModal';
import { OpenReadAssetModal } from '../mconfig/OpenReadAssetModal';
import { OpenMaterialModal } from '../mconfig/OpenMaterialModal';
import {
  addAssetApplyReturnSerivice,
  addAssetApplyUesSerivice,
  approvedAssetApplyReturnSerivice,
  approvedAssetApplyUseSerivice,
  dealNumAssetApplyUseSerivice,
  detailAssetApplyReturnServices,
  detailAssetApplyUesServices,
  editAssetApplyReturnSerivice,
  editAssetApplyUesSerivice,
  getStorageTreeService,
} from '../services';
import { DetailInfoViewBottomBtn } from '../mconfig/DetailInfoViewBottomBtn';
import { RevokeModal } from '@/pages/PurchaseManage/Acomponents/RevokeModal';
import { ExportModal } from './ExportModal';
import moment from 'moment';

/** 领用/退库 表单页 */
const UpdateView: React.FC<any> = ({ curRes, locationProps }) => {
  /** 引入上下文 */
  const { assetList, materialList, addAssetList, acquisitionDispatch } = useAcquisitionManageReducer();

  // 详情数据
  const [detailInfo, setDetailInfo] = useState<any>({});

  const [storeTreeList, setStoreTreeList] = useState<any>([]);

  /** 审批完成 */
  const [finish, setFinish] = useState<boolean>(false);

  /** 领用审批同意判断是否可以调用同步接口 */
  const [auditSuccessState, setAuditSuccessState] = useState(false);

  /**是否显示撤销弹窗*/
  const [invalidState, setInvalidState] = useState<Record<string, any>>({}); /**撤销弹窗*/

  /** 获取仓库树回调 */
  const updataGetStorage = (res: any) => {
    if (res && res?.msgFlag) {
      setStoreTreeList(res?.obj);
    }
  };

  /** 获取仓库树 */
  const { getStorageLoading, getStorageRun } = getStorageTreeService(updataGetStorage, curRes);

  /** ===================================================== 领用 / 借用 Serivice START ========================================== */
  /** 新增 */
  const { addAssetApplyUesRun, addAssetApplyUesLoading } = addAssetApplyUesSerivice((res) => {
    if (res && res?.msgFlag) {
      detailAssetApplyUesRun({ id: res?.obj?.id });
      // flag 表示点击的提交
      if (saveFlag == '1') {
        setDetailInfo({ ...detailInfo, id: res?.obj?.id });
        /** 发起审批 */
        setWorkFlowInfoObj({
          selectFlowRows: res?.obj,
          showWorkFlowModal: true,
          saveNoDefaultFlowID: '',
        });
      } else {
        message.success(res?.msg);
        history?.push({
          pathname: `/assetApplyUes/edit/:${getKeyRouter()}${getKeyRouter()}`,
          state: {
            pageType: 'edit',
            record: res?.obj,
            delRouterName: history?.location?.pathname,
          },
        });
      }
    } else {
      message.error(res?.msg);
    }
  });

  /** 详情 */
  const { detailAssetApplyUesRun, detailAssetApplyUesLoading } = detailAssetApplyUesServices((res) => {
    if (res && res?.msgFlag) {
      setDetailInfo(res?.obj);
      acquisitionDispatch({
        type: IAcquisitionActionEnum.SELECT_ASSET,
        payload: res?.obj?.applyNumberAssetList,
      });
      acquisitionDispatch({
        type: IAcquisitionActionEnum.SELECT_MATERIAL,
        payload: res?.obj?.applyNumberMaterialList,
      });

      /** 是否是审核中 */
      if (
        (res?.obj?.checkState === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1000` &&
          (res?.obj?.state === `${getTenantID()}${ILoadMapTypeAll.STORAGE_USE_STATUS}1001` ||
            res?.obj?.state === `${getTenantID()}${ILoadMapTypeAll.STORAGE_RETURN_STATUS}1001`)) ||
        res?.obj?.checkState === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1006`
      ) {
        setAuditSuccessState(true);
      }

      message.success(res?.msg);
    }
  });

  /** 编辑 */
  const { editAssetApplyUesRun, editAssetApplyUesLoading } = editAssetApplyUesSerivice((res) => {
    if (res && res?.msgFlag) {
      detailAssetApplyUesRun({ id: res?.obj?.id });
      // 复核时没有提交按钮
      // flag 表示点击的提交
      if (saveFlag == '1') {
        /** 发起审批 */
        setWorkFlowInfoObj({
          selectFlowRows: res?.obj,
          showWorkFlowModal: true,
          saveNoDefaultFlowID: '',
        });
      } else {
        message.success(res?.msg);
        detailAssetApplyUesRun({ id: locationProps?.state?.record?.id });
      }
    } else {
      message.error(res?.msg);
    }
  });

  /** 同步 */
  const { approvedAssetApplyUseRun, approvedAssetApplyUseLoading } = approvedAssetApplyUseSerivice((res) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      history.push({
        pathname: '/useAsReturnController/manage',
        state: {
          delRouterNameSource: history.location.pathname,
        },
      });
    } else {
      message.error(res?.msg);
    }
  });

  /** 校验锁定回退资产和物料数量 */
  const { dealNumAssetApplyUseRun, dealNumAssetApplyUseLoading } = dealNumAssetApplyUseSerivice((res) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      // setWorkFlowInfoObj({
      //   selectFlowRows: detailInfo,
      //   showWorkFlowModal: true,
      //   saveNoDefaultFlowID: '',
      // });
    }
  });

  /** ===================================================== 领用Serivice END ========================================== */

  /** ===================================================== 退库 / 归还 Serivice START========================================== */
  /** 新增 */
  const { addAssetApplyReturnRun, addAssetApplyReturnLoading } = addAssetApplyReturnSerivice((res) => {
    if (res && res?.msgFlag) {
      detailAssetApplyReturnRun({ id: res?.obj?.id });
      // setDetailInfo(res?.obj)
      // flag 表示点击的提交
      if (saveFlag == '1') {
        setWorkFlowInfoObj({
          selectFlowRows: res?.obj,
          showWorkFlowModal: true,
          saveNoDefaultFlowID: '',
        });
      } else {
        message.success(res?.msg);
        history?.push({
          pathname: `/assetApplyReturn/edit/:${getKeyRouter()}${getKeyRouter()}`,
          state: {
            pageType: 'edit',
            record: res?.obj,
            delRouterName: history?.location?.pathname,
          },
        });
      }
    } else {
      message.error(res?.msg);
    }
  });

  /** 详情 */
  const { detailAssetApplyReturnRun, detailAssetApplyReturnLoading } = detailAssetApplyReturnServices((res) => {
    if (res && res?.msgFlag) {
      setDetailInfo(res?.obj);
      acquisitionDispatch({
        type: IAcquisitionActionEnum.SELECT_ASSET,
        payload: res?.obj?.applyNumberAssetList,
      });
      acquisitionDispatch({
        type: IAcquisitionActionEnum.SELECT_MATERIAL,
        payload: res?.obj?.applyNumberMaterialList,
      });
      /** 是否是审核中 */
      if (
        res?.obj?.checkState === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1000` &&
        (res?.obj?.state === `${getTenantID()}${ILoadMapTypeAll.STORAGE_USE_STATUS}1001` ||
          res?.obj?.state === `${getTenantID()}${ILoadMapTypeAll.STORAGE_RETURN_STATUS}1001`)
      ) {
        setAuditSuccessState(true);
      }
      message.success(res?.msg);
    }
  });

  /** 编辑 */
  const { editAssetApplyReturnRun, editAssetApplyReturnLoading } = editAssetApplyReturnSerivice((res) => {
    if (res && res?.msgFlag) {
      // setDetailInfo(res?.obj)
      detailAssetApplyReturnRun({ id: res?.obj?.id });
      // flag 表示点击的提交
      if (saveFlag == '1') {
        setWorkFlowInfoObj({
          selectFlowRows: res?.obj,
          showWorkFlowModal: true,
          saveNoDefaultFlowID: '',
        });
      } else {
        message.success(res?.msg);
        detailAssetApplyReturnRun({ id: locationProps?.state?.record?.id });
      }
    } else {
      message.error(res?.msg);
    }
  });

  /** 同步 */
  const { approvedAssetApplyReturnRun, approvedAssetApplyReturnLoading } = approvedAssetApplyReturnSerivice((res) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      history.push({
        pathname: '/useAsReturnController/manage',
        state: {
          delRouterNameSource: history.location.pathname,
        },
      });
    } else {
      message.error(res?.msg);
    }
  });
  /** ===================================================== 退库Serivice END ========================================== */

  /** 样式根目录 */
  const styleFixCls = 'contract-styfixcls-';

  /** 表单 */
  const [useReturnForm] = Form.useForm();

  /** 选中的单位ID */
  const [selectUserInfo, setSelectUserInfo] = useState<Record<string, any>>({});

  /** 获取当前人对象 */
  const setSelectUserInfoFun = (option) => {
    setSelectUserInfo(option);
  };

  const [saveFlag, setSaveFlag] = useState<string>('0');

  /** 打开选择资产列表 */
  const [openAssetModal, setOpenAssetModal] = useState<boolean>(false);
  /** 打开查看资产列表 */
  const [openReadAssetModal, setOpenReadAssetModal] = useState<Record<string, any>>({});
  // 打开选择材料列表
  const [openMaterialModal, setOpenMaterialModal] = useState<boolean>(false);
  // 编辑状态
  const [editState, setEditState] = useState<boolean>(false);
  /** 选中的项的materialId */
  const [editAssetId, setEditAssetId] = useState<any>({});

  // 选中的项的materialId
  const changeEditAssetId = (id: string, index: number, text: any) => {
    let obj: any = {
      id,
      index: index,
      text,
    };
    setEditAssetId(obj);
  };

  // 打开选择资产列表方法
  const openAssetModalFun = () => {
    setOpenAssetModal(true);
  };

  // 打开查看我的资产列表方法
  const openReadAssetModalFun = () => {
    setOpenReadAssetModal({
      isShow: true,
      userID: methods?.getFieldValue('userID'),
    });
  };

  // 打开选择材料列表方法
  const openMaterialModalFun = () => {
    setOpenMaterialModal(true);
  };

  /** 复核审批阶段保存数据 */
  const handleEditSave = (assetData: Record<string, any>[]) => {
    // 校验选中的材料或资产
    if (assetData?.length === 0 && materialList?.length === 0) {
      message.error('请选择资产或材料!');
      return;
    }
    if (detailInfo?.applyType == 0 && (assetData?.length === 0 || materialList?.length === 0)) {
      message.error('请选择资产或材料!');
      return;
    }

    const params = {
      ...detailInfo,
      applyNumberAssetList: detailInfo?.applyType != 2 ? assetData : [], // 资产信息列表
      applyNumberMaterialList: detailInfo?.applyType != 1 ? materialList : [], // 材料信息列表
    };
    // 修改接口
    editAssetApplyUesRun(params);
  };

  // 是否显示导出弹窗
  const [isShowExportModal, setIsShowExportModal] = useState<Record<string, any>>({});

  // 导出资产
  const onClickExportAssetsMaterials = (key) => {
    setIsShowExportModal({
      isShow: true,
      key,
      resObj: detailInfo,
    });
  };

  /** 获取表单配置
   *  @pageType  传递的类型，是修改还是查看
   *  @record   当前项
   */
  const { config, methods, colLoading } = getUpdateConfig({
    pageType: locationProps?.state?.pageType ? locationProps?.state?.pageType : '',
    tkObj: locationProps?.state?.tkObj ? locationProps?.state?.tkObj : {},
    openAssetModalFun,
    openMaterialModalFun,
    useReturnForm,
    setSelectUserInfoFun,
    detailInfo,
    storeTreeList,
    getStorageLoading,
    editState,
    changeEditAssetId,
    finish,
    acquisitionDispatch,
    openReadAssetModalFun,
    handleEditSave,
    onClickExportAssetsMaterials,
    curRes,
  });

  // 工作流
  const [isShowWorkRecord, setIsShowWorkRecord] = useState<boolean>(false);
  const [showSwitchFlow, setShowSwitchFlow] = useState<boolean>(false);
  const [workFlowInfoObj, setWorkFlowInfoObj] = useState<Record<string, any>>({
    selectFlowRows: {},
    showWorkFlowModal: false,
    saveNoDefaultFlowID: '',
  });

  /** 暂存按钮  保存数据 */
  const handleSave = (flagTag: string) => {
    // 对表单进行校验，获取表单数据
    methods.validateFields()?.then((values: any) => {
      if (assetList?.length === 0 && materialList?.length === 0) {
        message.error('请选择资产明细或材料明细!');
        return;
      }
      if (values?.applyType == 0 && (assetList?.length === 0 || materialList?.length === 0)) {
        message.error('请选择资产明细或材料明细!');
        return;
      }

      // 校验退库的时候选择的资产有没有退回的仓库
      // if (values?.queryType == '2') {
      //   for (let i = 0; i < assetList.length; i++) {
      //     if (!assetList[i].assetStoreId) {
      //       message.error(`退库的第${i + 1}条资产没有选择退回仓库！`);
      //       return;
      //     }
      //     if (assetList[i].assetStoreState != null && assetList[i].assetStoreState !== 1) {
      //       message.error(`退库的第${i + 1}条资产选择的退回仓库状态已关闭，请选择其他仓库！`);
      //       return;
      //     }
      //   }
      // }

      const params = {
        ...values,
        applyNumberAssetList: values?.applyType != 2 ? assetList : [], // 资产信息列表
        applyNumberMaterialList: values?.applyType != 1 ? materialList : [], // 材料信息列表
        belongDepartmentID: values?.belongDepartmentID ? values?.belongDepartmentID : detailInfo?.belongDepartmentID,
        useCompanyID: selectUserInfo?.userCompanyID ? selectUserInfo?.userCompanyID : detailInfo?.useCompanyID,
        useDepartmentID: values?.useDepartmentID ? values?.useDepartmentID : detailInfo?.useDepartmentID,
        usePositionID: selectUserInfo?.userPositionID ? selectUserInfo?.userPositionID : detailInfo?.usePositionID,
        userID: selectUserInfo?.id ? selectUserInfo?.id : detailInfo?.userID,
      };

      /** 只有第一回是添加，其他都是暂存 */
      setSaveFlag(flagTag);
      /**
       * IF 新增接口判断
       * 申请类型 1:领用 2:退库 3:借用 4:归还
       * */
      if ((locationProps?.state?.pageType == 'add' && flagTag == '0' && !detailInfo?.id) || (flagTag == '1' && !detailInfo?.id)) {
        if (params?.queryType == '1' || params?.queryType == '3') {
          const tempParams = {
            ...params,
            userID: params.userID ? params.userID : getUserID(),
            usePositionID: params.usePositionID ? params.usePositionID : getPosIDs(),
            useDepartmentID: params.useDepartmentID ? params.useDepartmentID : getUserDepID(),
            useCompanyID: params.useCompanyID ? params.useCompanyID : getCompanyID(),
            createTime: moment(params?.createTime)?.format('YYYY-MM-DD HH:mm:ss'),
            backTime: moment(params?.backTime)?.format('YYYY-MM-DD HH:mm:ss'),
          };
          if (params?.queryType != '3') {
            delete tempParams['backTime'];
          }
          addAssetApplyUesRun(tempParams);
          setDetailInfo(tempParams);
        } else {
          delete params?.useCompanyID;
          delete params?.useDepartmentID;
          delete params?.usePositionID;
          delete params?.userID;
          const tempParams = {
            ...params,
            createTime: moment(params?.createTime)?.format('YYYY-MM-DD HH:mm:ss'),
            backTime: moment(params?.backTime)?.format('YYYY-MM-DD HH:mm:ss'),
          };
          if (params?.queryType != '3') {
            delete tempParams['backTime'];
          }
          addAssetApplyReturnRun(tempParams);
        }
      } else {
        /**
         * IF 编辑接口判断
         * 申请类型 1:领用 2:退库 3:借用 4:归还
         * */
        if (params?.queryType == '1' || params?.queryType == '3') {
          params.id = locationProps?.state?.record?.id || detailInfo?.id;
          let obj = {
            ...detailInfo,
            ...params,
            createTime: moment(params?.createTime)?.format('YYYY-MM-DD HH:mm:ss'),
            backTime: moment(params?.backTime)?.format('YYYY-MM-DD HH:mm:ss'),
          };
          if (params?.queryType != '3') {
            delete obj['backTime'];
          }
          editAssetApplyUesRun(obj);
        } else {
          params.id = locationProps?.state?.record?.id;
          delete params?.useCompanyID;
          delete params?.useDepartmentID;
          delete params?.usePositionID;
          delete params?.userID;
          let obj = {
            ...detailInfo,
            ...params,
            createTime: moment(params?.createTime)?.format('YYYY-MM-DD HH:mm:ss'),
            backTime: moment(params?.backTime)?.format('YYYY-MM-DD HH:mm:ss'),
          };
          if (params?.queryType != '3') {
            delete obj['backTime'];
          }
          editAssetApplyReturnRun(obj);
        }
      }
    });
  };

  /**
   * 关闭切换流程modal方法
   * @isDefaultModal  点击确定 true,关闭切换流程zujian,打开发起流程组件  点击取消 false 关闭切换流程组件
   */
  const closeSwitchFlowModal = (isDefaultModal: boolean) => {
    if (isDefaultModal) {
      setWorkFlowInfoObj({
        ...workFlowInfoObj,
        showWorkFlowModal: true,
      });
    } else {
      setShowSwitchFlow(false);
    }
  };

  /**
   * 处理工作流功能 权限
   */
  const workflowPowerAllBtn = useMemo(() => {
    let pownerBtn: Record<string, any> = {
      revokeFlagBtn: false, //撤销按钮
      invalBoolBtn: false, //暂停开始按钮
      stopProcInstBtn: false, //流程作废接口
    };
    if (detailInfo?.state == `${getTenantID()}${ILoadMapTypeAll?.DISCLOSURE_STATE}1001`) {
      pownerBtn['revokeFlagBtn'] = true;
      pownerBtn['stopProcInstBtn'] = true;
    }

    const taskType: string = `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1001`;
    const taskHandInfo: Record<string, any> = detailInfo?.paramObject?.[taskType];
    if (
      taskHandInfo &&
      taskHandInfo?.mactivitiTaskList?.length > 0 &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
    ) {
      pownerBtn['invalBoolBtn'] = true;
    }
    return pownerBtn;
  }, [detailInfo]);

  /** 初始化 */
  useEffect(() => {
    if (locationProps?.state?.tkObj) {
      acquisitionDispatch({
        type: IAcquisitionActionEnum.SELECT_ASSET,
        payload: [...locationProps?.state?.tkObj.assetList],
      });
    }
    getStorageRun();

    /**
     * IF 详情接口判断
     * 申请类型 1:领用 2:退库 3:借用 4:归还
     * */
    if (locationProps?.state?.pageType != 'add') {
      if (locationProps?.state?.record?.queryType == '1' || locationProps?.state?.record?.queryType == '3') {
        detailAssetApplyUesRun({ id: locationProps?.state?.record?.id });
      } else if (locationProps?.state?.record?.queryType == '2' || locationProps?.state?.record?.queryType == '4') {
        detailAssetApplyReturnRun({ id: locationProps?.state?.record?.id });
      }
    }
  }, []);

  /** 监听审核状态-审核通过后调用同步接口 */
  useEffect(() => {
    if (detailInfo?.queryType == '1' || detailInfo?.queryType == '3') {
      if (
        detailInfo?.checkState === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002` &&
        detailInfo?.state === `${getTenantID()}${ILoadMapTypeAll.STORAGE_USE_STATUS}1003`
      ) {
        setFinish(true);
      } else {
        setFinish(false);
      }
      if (
        auditSuccessState &&
        detailInfo?.checkState === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002` &&
        detailInfo?.state === `${getTenantID()}${ILoadMapTypeAll.STORAGE_USE_STATUS}1003`
      ) {
        approvedAssetApplyUseRun({ ...detailInfo, workflowResult: true });
      }
    } else {
      if (
        auditSuccessState &&
        detailInfo?.checkState === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002` &&
        detailInfo?.state === `${getTenantID()}${ILoadMapTypeAll.STORAGE_RETURN_STATUS}1003`
      ) {
        approvedAssetApplyReturnRun({ ...detailInfo, workflowResult: true });
      }
    }
  }, [detailInfo?.checkState, detailInfo?.state]);

  /** 监听审核状态-复核通过后可以编辑 */
  useEffect(() => {
    // /** 监听审核状态-领用 */
    // const taskType: string = LYflowBusinessType();
    // const taskHandInfo: Record<string, any> = detailInfo?.paramObject?.[taskType];
    // if (
    //   (
    //     detailInfo?.queryType == '1' &&
    //     (
    //       (
    //         taskHandInfo &&
    //         taskHandInfo?.mactivitiTaskList?.length > 0 &&
    //         taskHandInfo?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
    //         taskHandInfo?.mactivitiTaskList?.[0]?.assigneeID == getUserID() &&
    //         detailInfo?.checkState === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1006`
    //       ) ||
    //       !taskHandInfo)
    //   ) ||
    //   !detailInfo?.id
    // ) {
    //   //判断复核时否是可以编辑
    //   setEditState(false);
    // } else {
    //   setEditState(true);
    // }

    /**
     * false : 显示删除列
     * true : 不显示删除列
     * */

    if (detailInfo?.id) {
      if (detailInfo?.paramObject?.[LYflowBusinessType()]) {
        let taskInfoList = detailInfo?.paramObject?.[LYflowBusinessType()]?.mactivitiTaskList;
        if (taskInfoList && taskInfoList?.[0]?.assigneePositionID == getPosIDs() && taskInfoList?.[0]?.assigneeID == getUserID()) {
          if (detailInfo?.checkState === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1006`) {
            setEditState(false); // 可编辑
          } else {
            setEditState(true);
          }
        } else {
          setEditState(true);
        }
      } else {
        setEditState(true);
      }
    } else {
      setEditState(false);
    }
  }, [detailInfo?.checkState]);

  /** 撤销回调函数 */
  const revokeReloadCallback = async () => {
    if (detailInfo?.queryType == '1' || detailInfo?.queryType == '3') {
      await dealNumAssetApplyUseRun({ ...detailInfo, dealType: 'back' });
    }
  };

  /** 申请页ref */
  const { confirm } = Modal;

  const closeCurrent = () => {
    confirm({
      title: '关闭',
      icon: <QuestionCircleOutlined />,
      content: '确定要关闭当前页吗？',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        history.push({
          pathname: locationProps?.state?.returnPathName,
          state: {
            delRouterNameSource: history.location.pathname, //必传,要删除的路由名称
            returnPathName: locationProps?.state?.returnPathName,
          },
        });
      },
      onCancel() {},
    });
  };

  /** 返回tab子页面 */
  const tabsItem = () => {
    let items: any[] = [
      {
        label: '申请详情',
        key: '001',
        children: (
          <div className="commonTabsBodyDom">
            <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
              <ScrollBarLayout style={{ padding: '5px 20px' }}>
                <DescriptionsType config={config} />
              </ScrollBarLayout>
            </div>
            <div className="tabsBodyBottomBtn">
              <Space>
                {/* {(locationProps?.state?.pageType != 'detail' && detailInfo?.createrID == getUserID()) ||
                  ((detailInfo?.state == `${getTenantID()}${ILoadMapTypeAll.STORAGE_USE_STATUS}1000` ||
                    detailInfo?.state == `${getTenantID()}${ILoadMapTypeAll.STORAGE_RETURN_STATUS}1000`) &&
                    !detailInfo?.checkState &&
                    detailInfo?.createrID == getUserID()) ||
                  locationProps?.state?.pageType === 'add' ? (
                  <Button
                    type={'primary'}
                    onClick={() => handleSave('1')}
                  >
                    提交
                  </Button>
                ) : null} */}

                {(detailInfo?.state == `${getTenantID()}${ILoadMapTypeAll.STORAGE_USE_STATUS}1000` ||
                  detailInfo?.state == `${getTenantID()}${ILoadMapTypeAll.STORAGE_RETURN_STATUS}1000`) &&
                  !detailInfo?.checkState &&
                  curRes?.['/assetApplyUes/startProcess/{starterDeptID}'] &&
                  curRes?.['/assetApplyReturn/startProcess/{starterDeptID}'] && (
                    <Button type={'primary'} onClick={() => handleSave('1')}>
                      提交
                    </Button>
                  )}

                <Button danger onClick={closeCurrent}>
                  关闭
                </Button>
              </Space>
            </div>
          </div>
        ),
      },
    ];
    return items;
  };

  const revokeReloadCallback1 = async () => {
    if (invalidState?.resObj?.queryType == '1' || invalidState?.resObj?.queryType == '3') {
      await dealNumAssetApplyUseRun({ ...invalidState?.resObj, dealType: 'back' });
      history.push({
        pathname: locationProps?.state?.returnPathName,
        state: {
          delRouterNameSource: history.location.pathname, //必传,要删除的路由名称
          returnPathName: locationProps?.state?.returnPathName,
        },
      });
    } else {
      history.push({
        pathname: locationProps?.state?.returnPathName,
        state: {
          delRouterNameSource: history.location.pathname, //必传,要删除的路由名称
          returnPathName: locationProps?.state?.returnPathName,
        },
      });
    }
  };

  const changeRevoke = () => {
    setInvalidState({
      isShow: true,
      resObj: detailInfo,
    });
  };

  /** tabs 标签页操作 */
  const contactsTabsExtra = () => {
    return (
      <DetailInfoViewBottomBtn
        position="top"
        detailInfo={detailInfo}
        locationProps={locationProps}
        handleSave={handleSave}
        detailAssetApplyUesRun={detailAssetApplyUesRun}
        detailAssetApplyReturnRun={detailAssetApplyReturnRun}
        revokeReloadCallback={revokeReloadCallback}
        changeRevoke={changeRevoke}
        curRes={curRes}
      />
    );
  };

  return (
    <>
      <AcquisitionManageContext.Provider
        value={{
          rightTableProps: {
            dataSource: [],
            assetForm: {},
            loading: false,
            getAcquisitionTableData: ({}) => {},
            mapList: [],
            pagination: {},
            otherParams: {},
            searchList: [],
            reloadTableData: () => {},
          },
          assetList,
          materialList,
          addAssetList,
          curRes,
          useReturnForm,
          acquisitionDispatch,
        }}
      >
        <div className={'asset-apply-update-UpdataIntentBox'}>
          <Spin
            spinning={
              addAssetApplyUesLoading ||
              detailAssetApplyUesLoading ||
              editAssetApplyUesLoading ||
              addAssetApplyReturnLoading ||
              detailAssetApplyReturnLoading ||
              editAssetApplyReturnLoading ||
              approvedAssetApplyUseLoading ||
              dealNumAssetApplyUseLoading ||
              approvedAssetApplyReturnLoading ||
              getStorageLoading ||
              colLoading
              // syncPDFtoOALoading
            }
          >
            <Row className={`${styleFixCls}row`}>
              <Col span={24} className={`${styleFixCls}row-col`}>
                <Tabs
                  className={pageStyles['commonTabs']}
                  type="card"
                  onChange={(activeKey: string) => {}}
                  items={tabsItem()}
                  destroyInactiveTabPane={true}
                  tabBarExtraContent={contactsTabsExtra()}
                />
              </Col>
            </Row>

            <div>
              {/* 名下资产弹窗 */}
              {openReadAssetModal?.isShow && (
                <OpenReadAssetModal curRes={curRes} onClose={() => setOpenReadAssetModal({})} userID={openReadAssetModal?.userID} />
              )}

              {/* 选择资产弹窗 */}
              {openAssetModal && (
                <OpenAssetModal
                  curRes={curRes}
                  isShowModal={openAssetModal}
                  editState={editState}
                  editAssetId={editAssetId}
                  handleEditSave={handleEditSave}
                  onClose={() => setOpenAssetModal(false)}
                  queryType={methods?.getFieldValue('queryType')}
                  BelongDepartmentID={async () => {
                    const formVal = await methods.getFieldValue('belongDepartmentID');
                    return formVal;
                  }}
                  detailInfo={detailInfo}
                />
              )}

              {/* 选择材料弹窗*/}
              {openMaterialModal && (
                <OpenMaterialModal
                  curRes={curRes}
                  isShowModal={openMaterialModal}
                  queryType={methods?.getFieldValue('queryType')}
                  BelongDepartmentID={async () => {
                    const formVal = await methods.getFieldValue('belongDepartmentID');
                    return formVal;
                  }}
                  onClose={() => setOpenMaterialModal(false)}
                />
              )}
            </div>

            {/* 工作流-----审批记录 */}
            {(detailInfo?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1011`] ||
              detailInfo?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1013`]) && (
              <WorkflowChedkRecord
                curRes={curRes}
                dataDetailInfo={detailInfo}
                flowBusinessType={
                  detailInfo?.queryType == '1' || detailInfo?.queryType == '3'
                    ? `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1011`
                    : `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1013`
                }
                requestController={detailInfo?.queryType == '1' ? LYrequestController() : TKrequestController()}
                reloadPageCallback={() => {
                  if (methods?.getFieldValue('queryType') === '1') {
                    detailAssetApplyUesRun({ id: detailInfo?.id });
                  } else {
                    detailAssetApplyReturnRun({ id: detailInfo?.id });
                  }
                }} // 刷新方法-详情方法
                revokeStateID={
                  detailInfo?.queryType == '1' || detailInfo?.queryType == '3'
                    ? `${getTenantID()}${ILoadMapTypeAll?.STORAGE_USE_STATUS}1000`
                    : `${getTenantID()}${ILoadMapTypeAll?.STORAGE_RETURN_STATUS}1000`
                }
                allBtnFuncQuqry={workflowPowerAllBtn}
                tabPaneHeight={0.35}
                isCheckDrawer={true}
                isShowCollapse={isShowWorkRecord}
                changeCollapse={(val) => {
                  setIsShowWorkRecord(val);
                }}
                cancelStateId={
                  detailInfo?.queryType == '1' || detailInfo?.queryType == '3'
                    ? `${getTenantID()}${ILoadMapTypeAll?.STORAGE_USE_STATUS}1003`
                    : `${getTenantID()}${ILoadMapTypeAll?.STORAGE_RETURN_STATUS}1003`
                }
                isSyncArchive={true}
              />
            )}

            {/* 工作流-----发起流程审批弹窗 */}
            {workFlowInfoObj?.showWorkFlowModal && (
              <WorkflowSwitchModal
                openVisible={workFlowInfoObj?.showWorkFlowModal}
                businessInfoObj={{
                  ...workFlowInfoObj?.selectFlowRows,
                  busiDepartmentID:
                    (workFlowInfoObj?.selectFlowRows?.queryType == '1' || workFlowInfoObj?.selectFlowRows?.queryType == '3') &&
                    workFlowInfoObj?.selectFlowRows?.busiFlag == 1
                      ? workFlowInfoObj?.selectFlowRows?.busiDepartmentID
                      : null,
                }}
                requestController={
                  workFlowInfoObj?.selectFlowRows?.queryType == '1' || workFlowInfoObj?.selectFlowRows?.queryType == '3'
                    ? LYrequestController()
                    : TKrequestController()
                }
                orderType={
                  workFlowInfoObj?.selectFlowRows?.orderType ||
                  (workFlowInfoObj?.selectFlowRows?.queryType == '1' || workFlowInfoObj?.selectFlowRows?.queryType == '3' ? LYOrderType() : TKOrderType())
                }
                category={
                  workFlowInfoObj?.selectFlowRows?.queryType == '1' || workFlowInfoObj?.selectFlowRows?.queryType == '3'
                    ? `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1011`
                    : `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1013`
                }
                // TODO:资产暂时注释【领用退库-流程图bug】
                businessCategory={
                  workFlowInfoObj?.selectFlowRows?.queryType == '1' || workFlowInfoObj?.selectFlowRows?.queryType == '3'
                    ? `${getTenantID()}${ILoadMapTypeAll.ASSET_APPLY_CATEGORY}1000`
                    : `${getTenantID()}${ILoadMapTypeAll.ASSET_RETURN_CATEGORY}1000`
                }
                // businessCategory={''}
                selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
                reloadInfoCallback={async () => {
                  if (detailInfo?.queryType == '1' || detailInfo?.queryType == '3') {
                    await dealNumAssetApplyUseRun({ ...detailInfo, dealType: 'start' });
                    history.push({
                      pathname: '/useAsReturnController/manage',
                      state: {
                        delRouterNameSource: history.location.pathname,
                      },
                    });
                  } else {
                    history.push({
                      pathname: '/useAsReturnController/manage',
                      state: {
                        delRouterNameSource: history.location.pathname,
                      },
                    });
                  }
                }}
                openFlowChangeModal={setShowSwitchFlow}
                onClose={() => {
                  setWorkFlowInfoObj({
                    ...workFlowInfoObj,
                    showWorkFlowModal: false,
                  });
                  history.push({
                    pathname: '/useAsReturnController/manage',
                    state: {
                      delRouterNameSource: history.location.pathname,
                    },
                  });
                }}
                replaceStrObj={{ own: 'own', workflowType: 'category' }}
              />
            )}

            {/* 撤销弹窗 */}
            {invalidState?.isShow && (
              <RevokeModal
                resObj={invalidState?.resObj}
                revokeRequestUrl={
                  invalidState?.resObj?.queryType == '1' || invalidState?.resObj?.queryType == '3' ? '/assetApplyUes/revoke' : '/assetApplyReturn/revoke'
                }
                onClose={() => setInvalidState({})}
                reqBody={{
                  id: invalidState?.resObj?.id,
                  state:
                    invalidState?.resObj?.queryType == '1' || invalidState?.resObj?.queryType == '3'
                      ? `${getTenantID()}${ILoadMapTypeAll?.STORAGE_USE_STATUS}1000`
                      : `${getTenantID()}${ILoadMapTypeAll?.STORAGE_RETURN_STATUS}1000`,
                }}
                modalTip={
                  <div style={{ color: '#000' }}>
                    确认是否撤销【<span style={{ color: 'red' }}>{invalidState?.resObj?.applyTitle}</span>】的审核, 撤销后可重新提交！
                  </div>
                }
                reloadRequest={revokeReloadCallback1}
              />
            )}

            {/* 挑选流程组件 */}
            {showSwitchFlow && (
              <WorkflowNoDefaultTable
                openVisibleSwitch={showSwitchFlow}
                onCloseSwitch={closeSwitchFlowModal}
                requestController={
                  workFlowInfoObj?.selectFlowRows?.queryType == '1' || workFlowInfoObj?.selectFlowRows?.queryType == '3'
                    ? LYrequestController()
                    : TKrequestController()
                }
                orderType={
                  workFlowInfoObj?.selectFlowRows?.orderType ||
                  (workFlowInfoObj?.selectFlowRows?.queryType == '1' || workFlowInfoObj?.selectFlowRows?.queryType == '3' ? LYOrderType() : TKOrderType())
                }
                category={
                  workFlowInfoObj?.selectFlowRows?.queryType == '1' || workFlowInfoObj?.selectFlowRows?.queryType == '3'
                    ? `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1011`
                    : `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1013`
                }
                businessCategory={``}
                saveSelectFlowID={(flowId: string) => {
                  setWorkFlowInfoObj({
                    ...workFlowInfoObj,
                    saveNoDefaultFlowID: flowId,
                  });
                }}
                selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
              />
            )}

            {/* 导出资产/材料弹窗 */}
            {isShowExportModal?.isShow && <ExportModal onClose={() => setIsShowExportModal({})} reqParams={{ ...isShowExportModal }} />}
          </Spin>
        </div>
      </AcquisitionManageContext.Provider>
    </>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(UpdateView);
